package com.springboot.demo.class_loader;

import java.io.IOException;
import java.io.InputStream;

/**
 * 自定义加载器
 *
 * @author supu
 * @date 2019-06-25 14:46
 **/
public class CustomClassLoader extends ClassLoader {

    public CustomClassLoader(ClassLoader parent) {
        super(parent);
    }

    /*@Override
    public Class<?> loadClass(String name)
            throws ClassNotFoundException {
        String fileName = name.substring(name.lastIndexOf(".") + 1) + ".class";
        InputStream is;
        try {
            is = getClass().getResourceAsStream(fileName);
            if (is == null) {
                return super.loadClass(fileName);
            }
            byte[] by = new byte[is.available()];
            is.read(by);
            is.close();
            return defineClass(name, by, 0, by.length);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }*/

    @Override
    public Class<?> findClass(String name) throws ClassNotFoundException {
        byte[] by = null;
        try {
            by = getByteByClassName(name);
            return defineClass(name, by, 0, by.length);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return super.findClass(name);
    }

    private byte[] getByteByClassName(String name) throws IOException {
        String fileName = name.substring(name.lastIndexOf(".") + 1) + ".class";
        InputStream is = getClass().getResourceAsStream(fileName);
        byte[] by = new byte[is.available()];
        is.read(by);
        is.close();
        return by;
    }
}
